"""
项目服务
"""
from flask_login import current_user
from datetime import datetime
from app.models import Project, ProjectTask, ProjectMilestone, ProjectRole, User, get_db

class ProjectService:
    """项目服务类"""
    
    @staticmethod
    def get_projects(page=1, per_page=10):
        """获取项目列表"""
        db = get_db()
        projects = Project.query.filter_by(manager_id=current_user.id).paginate(
            page=page, per_page=per_page, error_out=False)
        return projects
    
    @staticmethod
    def get_project(project_id):
        """获取单个项目"""
        db = get_db()
        project = Project.query.get_or_404(project_id)
        
        # 检查权限
        if project.manager_id != current_user.id:
            return None
        
        return project
    
    @staticmethod
    def create_project(name, description, start_date, end_date, project_type=None, project_source=None, estimated_budget=0.0, status='planning', manager_id=None, customer_id=None):
        """创建项目"""
        db = get_db()
        
        # 如果没有指定manager_id，使用当前用户
        if manager_id is None:
            manager_id = current_user.id
        
        project = Project(
            name=name,
            description=description,
            start_date=start_date,
            end_date=end_date,
            project_type=project_type,
            project_source=project_source,
            estimated_budget=estimated_budget,
            status=status,
            manager_id=manager_id,
            customer_id=customer_id
        )
        
        db.session.add(project)
        db.session.commit()
        
        return project
    
    @staticmethod
    def update_project(project_id, name, description, start_date, end_date, project_type=None, project_source=None, estimated_budget=None, status=None):
        """更新项目"""
        db = get_db()
        project = Project.query.get_or_404(project_id)
        
        # 检查权限
        if project.manager_id != current_user.id:
            return False
        
        project.name = name
        project.description = description
        project.start_date = start_date
        project.end_date = end_date
        
        if project_type is not None:
            project.project_type = project_type
        if project_source is not None:
            project.project_source = project_source
        if estimated_budget is not None:
            project.estimated_budget = estimated_budget
        if status is not None:
            project.status = status
        
        db.session.commit()
        
        return True
    
    @staticmethod
    def delete_project(project_id):
        """删除项目"""
        db = get_db()
        project = Project.query.get_or_404(project_id)
        
        # 检查权限
        if project.manager_id != current_user.id:
            return False
        
        db.session.delete(project)
        db.session.commit()
        
        return True
    
    @staticmethod
    def create_task(project_id, name, description, start_date=None, end_date=None, priority='medium', assigned_to=None):
        """创建项目任务"""
        db = get_db()
        project = Project.query.get_or_404(project_id)
        
        # 检查权限
        if project.manager_id != current_user.id:
            return None
        
        task = ProjectTask(
            project_id=project_id,
            name=name,
            description=description,
            start_date=start_date,
            end_date=end_date,
            priority=priority,
            assigned_to=assigned_to,
            status='pending'
        )
        
        db.session.add(task)
        db.session.commit()
        
        return task
    
    @staticmethod
    def get_project_tasks(project_id):
        """获取项目任务列表"""
        db = get_db()
        project = Project.query.get_or_404(project_id)
        
        # 检查权限
        if project.manager_id != current_user.id:
            return None
        
        tasks = ProjectTask.query.filter_by(project_id=project_id).all()
        return tasks
    
    @staticmethod
    def get_project_tasks_paginated(project_id, user_id=None, page=1, per_page=10):
        """获取项目任务分页数据"""
        db = get_db()
        project = Project.query.get_or_404(project_id)
        
        # 检查权限
        if project.manager_id != current_user.id:
            return None
        
        # 获取分页的任务数据
        tasks_pagination = ProjectTask.query.filter_by(project_id=project_id).paginate(
            page=page, per_page=per_page, error_out=False)
        
        return tasks_pagination
    
    @staticmethod
    def create_milestone(project_id, name, description, due_date):
        """创建项目里程碑"""
        db = get_db()
        project = Project.query.get_or_404(project_id)
        
        # 检查权限
        if project.manager_id != current_user.id:
            return None
        
        milestone = ProjectMilestone(
            project_id=project_id,
            name=name,
            description=description,
            due_date=due_date,
            status='pending'
        )
        
        db.session.add(milestone)
        db.session.commit()
        
        return milestone
    
    @staticmethod
    def get_project_milestones(project_id):
        """获取项目里程碑列表"""
        db = get_db()
        project = Project.query.get_or_404(project_id)
        
        # 检查权限
        if project.manager_id != current_user.id:
            return None
        
        milestones = ProjectMilestone.query.filter_by(project_id=project_id).all()
        return milestones
    
    @staticmethod
    def get_project_roles_paginated(project_id, page=1, per_page=10):
        """获取项目角色分页数据"""
        db = get_db()
        project = Project.query.get_or_404(project_id)
        
        # 检查权限
        if project.manager_id != current_user.id:
            return None
        
        # 直接查询数据库表，避免使用BaseModel的分页方法
        from sqlalchemy import text
        
        # 获取总数
        count_query = text("SELECT COUNT(*) FROM project_role WHERE project_id = :project_id")
        total = db.session.execute(count_query, {"project_id": project_id}).scalar()
        
        # 获取分页数据
        offset = (page - 1) * per_page
        query = text("""
            SELECT pr.*, u.username, u.email 
            FROM project_role pr 
            LEFT JOIN user u ON pr.user_id = u.id 
            WHERE pr.project_id = :project_id 
            LIMIT :limit OFFSET :offset
        """)
        results = db.session.execute(query, {
            "project_id": project_id,
            "limit": per_page,
            "offset": offset
        }).fetchall()
        
        # 创建分页对象
        class Pagination:
            def __init__(self, page, per_page, total, items):
                self.page = page
                self.per_page = per_page
                self.total = total
                self.items = items
                self.pages = (total + per_page - 1) // per_page
                self.has_prev = page > 1
                self.has_next = page < self.pages
                self.prev_num = page - 1 if self.has_prev else None
                self.next_num = page + 1 if self.has_next else None
            
            def iter_pages(self, left_edge=2, left_current=2, right_current=3, right_edge=2):
                """生成分页页码列表"""
                last = 0
                for num in range(1, self.pages + 1):
                    if num <= left_edge or \
                       (num > self.page - left_current - 1 and \
                        num < self.page + right_current) or \
                       num > self.pages - right_edge:
                        if last + 1 != num:
                            yield None
                        yield num
                        last = num
        
        # 转换结果为字典列表
        items = []
        for row in results:
            item = {
                'id': row[0],
                'project_id': row[1],
                'user_id': row[2],
                'role': row[3],
                'department': row[4],
                'position': row[5],
                'username': row[6],
                'email': row[7]
            }
            items.append(item)
        
        return Pagination(page, per_page, total, items)